package com.lirh.mywebsocket.stompController;

import com.lirh.mywebsocket.pojo.Question;
import com.lirh.mywebsocket.vo.RequestMessage;
import com.lirh.mywebsocket.vo.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.HtmlUtils;

import java.util.ArrayList;

@RestController
public class StompTestController {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    /**
     * 聊天室（单聊+多聊）
     */
    @CrossOrigin
    @MessageMapping("/chat")
    public void messageHandling(RequestMessage requestMessage) throws Exception{
        System.out.println(requestMessage);
        String destination="/topic/"+HtmlUtils.htmlEscape(requestMessage.getRoom());
//        String sender=HtmlUtils.htmlEscape(requestMessage.getSender());
//        String type=HtmlUtils.htmlEscape(requestMessage.getType());
//        String content=HtmlUtils.htmlEscape(requestMessage.getContent());
//        ResponseMessage response = new ResponseMessage(sender, type, content);
        messagingTemplate.convertAndSend(destination,requestMessage.getName()+": "+requestMessage.getContent());
    }
    /**
     * 群发消息
     */
    @CrossOrigin
    @MessageMapping("/chatAll")
    public void messageHandlingAll(RequestMessage requestMessage) throws Exception{
        String destination="/all";
//        String sender=HtmlUtils.htmlEscape(requestMessage.getSender());
//        String type=HtmlUtils.htmlEscape(requestMessage.getType());
//        String content=HtmlUtils.htmlEscape(requestMessage.getContent());
//        ResponseMessage response = new ResponseMessage(sender, type, content);
        messagingTemplate.convertAndSend(destination,requestMessage.getRoom()+"房间 "+requestMessage.getName()+": "+requestMessage.getContent());
    }
    @MessageMapping("/all")
    @SendTo("/all")
    public String sendtoall(RequestMessage requestMessage){
        return "【全体消息】 "+requestMessage.getName()+":"+requestMessage.getContent();
    }

    @GetMapping("/getSelfQuestions")
    public ArrayList<Question> getSelfQuestions(){
        ArrayList<Question> questionArrayList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Question question = new Question();
            question.setId(i+"");
            question.setSubject("语文");
            question.setAnswer("答案");
            question.setCreateTime(System.currentTimeMillis());
            questionArrayList.add(question);
        }
        return questionArrayList;
    }

}
